
// 16进制转换成rgb
let hexToRgb = color => {
    let hex = color.slice(1,7);
    let r, g, b;
    r = parseInt(hex.slice(0,2),16);
    g = parseInt(hex.slice(2,4),16);
    b = parseInt(hex.slice(4,6),16);
    return [r,g,b]

};
function scrollToZoro() {
    window.scrollTo(0, 0);
}
function closeTab(){
    $('#contentTab').css({'display':'none'});
    $('#contentTab>.tab').remove();
};
const imgList = [{src : '/static/svg/sport01.svg'},{src : '/static/svg/sport02.svg'},{src : '/static/svg/sport03.svg'},{src : '/static/svg/sport04.svg'},{src : '/static/svg/sport05.svg'},
{src : '/static/svg/sport06.svg'},{src : '/static/svg/sport07.svg'},{src : '/static/svg/sport08.svg'},{src : '/static/svg/sport09.svg'},{src : '/static/svg/sport10.svg'},
{src : '/static/svg/sport11.svg'},{src : '/static/svg/sport12.svg'},{src : '/static/svg/sport13.svg'},{src : '/static/svg/sport14.svg'},{src : '/static/svg/sport15.svg'},
{src : '/static/svg/sport16.svg'}];

const materialColor = [{'color':'blue', 'src' :'/static/materialColor/blue.png'},{'color':'white', 'src' :'/static/materialColor/white.png'},{'color':'red', 'src' :'/static/materialColor/red.png'},  {'color':'yellow', 'src' :'/static/materialColor/yellow.png'},{'color':'black', 'src' :'./materialColor/black.png'}, {'color':'orange', 'src' :'/static/materialColor/orange.png'}];
const stripeColor = [{'color':'#ff0000'},{'color':'#ffff00'},{'color':'#ffffff'},{'color':'#000000'},{'color':'#2b2b2b'},{'color':'#00ffff'},{'color':'#00ff00'},{'color':'#0000ff'},{'color':'#b3b3b3'},{'color':'#011341'}];
let materialType = 'material01';
let stripeImg = ['public/img/stripe01.png','public/img/stripe02.png','public/img/stripe03.png'];
let materialColorFlag = 'blue';
let stripeColorFlag = hexToRgb('#011341');
let keyFlag = true;
let indexFlag;  //判断当前选中的小球序号
let changeMaterialFlag;
let addMaterial;    //添加小球方法
let classArr = [];
let canvas;
let alertTable;
let createPicTab;
window.addEventListener('load', () => {
    //创建一个canvas;
    let initCanvas = () => {
        $('#canvasTab').html(`
            <canvas id=cv width=${256} height=${256}></canvas>
        `);
        canvas = new fabric.Canvas('cv');
    }
    initCanvas();

    let changeMaterialColor = (materialColor, stripeColor, type) => {
            document.querySelector('#inset').style.display = 'block';
            let formData = new FormData();
            formData.append('materialColor', materialColor);
            formData.append('stripeColor', stripeColor);
            formData.append('type', type);
            formData.append('stripeImg', stripeImg);
            fetch('http://192.168.3.21:8888/changeMaterialColor',{
                method: 'post',
                body : formData,
            }).then( res => {
                return res.json();
            }).then( res => {
                document.querySelector('#inset').style.display = 'none';
                let {imagePath} = res;
                console.log(res);
                if (res.code == 200 ) {
                    app.ExternalInterface.changeTexture('UV衣服', 'Texture.003', '/static'+imagePath.clothes.split('public')[1]);
                    app.ExternalInterface.changeTexture('UV裤子', 'Texture.001', '/static'+imagePath.pants.split('public')[1]);
                    app.ExternalInterface.changeTexture('UV裤头', 'Texture.007', '/static'+imagePath.belt.split('public')[1]);
                }
            });
    }
    $('#cvBlock').on({
        'swipeUp': () => {
              console.log(keyFlag)
            if (keyFlag) {
                classArr.push(classArr.shift());
                classArr.find((v, i) => {
                    $('#operation ul>li').eq(i).removeClass();
                    $('#operation ul>li').eq(i).addClass(v);
                });
            }
        },
        'swipeDown': () => {
            if (keyFlag) {
                classArr.unshift(classArr.pop());
                classArr.find((v, i) => {
                    $('#operation ul>li').eq(i).removeClass();
                    $('#operation ul>li').eq(i).addClass(v);
                });
            }
        },
        'doubleTap': () => {
           console.log('双击');
           classArr = [];
           $('#cvBlock').css({'display': 'none'});
           $('#operation').css({'display': 'none'});
        },

    });

    
    let changeColor = (imgData,imgSrc) => {
        switch(changeMaterialFlag) {
            case 'collar':
                addMaterial(materialColor);
                app.ExternalInterface.changeTexture('UV衣领', 'Texture.020', imgSrc);
                break;
            case 'clothes':
                materialColorFlag = imgData;
                console.log(`imgData==${imgData}`);
                console.log(`materialColorFlag==${materialColorFlag}`);
                console.log(`stripeColorFlag==${stripeColorFlag}`);
                console.log(`materialType==${materialType}`);
                addMaterial(materialColor);
                changeMaterialColor(materialColorFlag, stripeColorFlag, materialType);
                break;
            case 'stripe':
                stripeColorFlag = hexToRgb(imgData);
                console.log(`imgData==${imgData}`);
                console.log(`materialColorFlag==${materialColorFlag}`);
                console.log(`stripeColorFlag==${stripeColorFlag}`);
                console.log(`materialType==${materialType}`);
                addMaterial(stripeColor);
                changeMaterialColor(materialColorFlag, stripeColorFlag, materialType);
                break;
            default:
                console.log('无此类型');
                break;
        }
    }
    addMaterial = (data) => {
        console.log(data)
       
        console.log(classArr);
        const ulStyle = `width: 100%; height: 100%;`;
        $('#operation').html(`
            <ul style = '${ulStyle}' >                                                                 
            ${data.map((v, i) => `
                <li colorFlag='${v.color}' colorSrc='${v.src ? v.src : v.color}' class = '${classArr[i]} ${ i == indexFlag ? 'iconfont icon-dagou' : '' }' style = 'background:${v.color};  ${ i == indexFlag ? 'font-size: 2rem; line-height: 2.8rem; text-align: center; color: green; opacity: 0.8; ' : ''} ' >
                
                </li>
                `).join('')} 
            </ul>
        `);
        let clientWidth = document.documentElement.clientWidth;
        let ca = `
            <canvas id=cover width=${375 * clientWidth / 375} height=${ 667 * clientWidth / 375}></canvas>
        `;
        $('#cvBlock').html(ca)
        let canvas2 = new fabric.Canvas('cover');
        canvas2.selection = false; //禁用组选择
       
    }
    document.querySelector('#operation').ontouchstart = e => {
        e.preventDefault();
        keyFlag = false;
       
        $(e.target).css({'transition': '0s ease all 0s '});
        //cx,cy为点击下去的落点坐标
        let cx = e.touches[0].clientX;
        let cy = e.touches[0].clientY;

        //left,top 为小球所在的位置
        let left = parseInt($(e.target).css('left'));
        let top = parseInt($(e.target).css('top'));

        //cLeft, cTop 为中心圆的坐标
        cLeft = parseInt($('#centerCircle').css('left')) + 2 * 50;
        cTop = parseInt($('#centerCircle').css('top')) + 2 * 50;

        let per = document.documentElement.clientWidth / 375;
        let distance;
        let ownDistance;  //小球距离原位置的距离
        document.ontouchmove = e => {
            $('#centerCircle').css({'display': 'block'})
            //disX 为手指拖动小球与小球刚开始位置的差
            let disX = left + e.touches[0].clientX - cx;
            let disY = top + e.touches[0].clientY - cy;
            $(e.target).css({'left': `${disX}px`, 'top': `${disY}px`});
            let disCenterX = disX + 1.4 * 50;
            let disCenterY = disY + 1.4 * 50;

            ownDistance = Math.sqrt(Math.pow(disX - left, 2) + Math.pow(disY - top, 2));

            // 拖动的元素距离圆心的距离
            distance = parseInt(Math.sqrt(Math.pow((disCenterX - cLeft), 2) + Math.pow((disCenterY - cTop), 2)));

            if (distance < 30) {
                $('#centerCircle').css({'backgroundColor': 'rgba(255,255,255,.8)'});
            } else {

                $('#centerCircle').css({'backgroundColor': 'rgba(255,255,255,.3)'})

            }
        }
        document.ontouchend = () => {
            let pointer = [...document.querySelectorAll('#operation ul>li')].indexOf(e.target);
            let imgSrc = $(e.target).attr('colorSrc');
            let imgColor = $(e.target).attr('colorFlag');
            if (!ownDistance) {
                console.log('点击换色')
                indexFlag = pointer;
                console.log(`indexFlag==${indexFlag}`);
                changeColor(imgColor,imgSrc);
            }

            if (distance < 30) {
                console.log('拖拽换色')
                indexFlag = pointer;
                console.log(`indexFlag==${indexFlag}`)
                changeColor(imgColor,imgSrc);
            }
            $('#centerCircle').css({'backgroundColor': 'rgba(255,255,255,.3)', 'display': 'none'});
            $(e.target).css({'transition': '.75s ease all 0s', 'left': `${left}px`, 'top': `${top}px`});
            document.ontouchmove = document.ontouchend = null;
            setTimeout(() => {
                keyFlag = true;
            }, 500);

        }
    }

     
    alertTable = (msg,type)=>{
        //获取用户信息
       //如果用户没有地址，显示添加新地址并跳转,新用户首次下单才会出现
       
       let modal='position: absolute; width: 12.8rem;height: 5.8rem;background: white;left:0;top:0;right:0;bottom:0;margin:auto;z-index:1001; user-select:none; border-radius: 10px; '
       let center='position:relative;width:100%;height:3.6rem; color: rgb(140,140,140); border-bottom:1px solid rgb(220,220,220); text-align: center; line-height: 3.6rem; font-size: .7rem; ';
       let bottom='position:relative;width:100%;height: 2.2rem;';
       let btn='float:left; width: 6.35rem;  line-height: 2.2rem; text-align: center; height: 100%;  color: black; font-size: .6rem; ';
       let btn2='float:left;  width: 6.4rem; height: 100%; line-height: 2.2rem; border-right: 1px solid rgb(220,220,220); text-align: center;  color: rgb(67,181,59); font-size: .6rem; ';
       let oDiv=`
           <div style='${modal}' class='tab'>
               <div style='${center}'>
                    <span>${msg}</span> <input id='numValue' type='text' maxlength='${type == 'num' ? 2 : 10}' style='border: 1px solid #ccc;' />
               </div>
               <div style='${bottom}'>
                   <div style='${btn2}' id='confirmNumBtn'>确定</div>
                   <div style='${btn}' onclick='closeTab()'>取消</div>
               </div>
           </div>
       `;
       $('#contentTab').html(oDiv);
       $('#contentTab').css({'display':'block'});
       $('#confirmNumBtn').on('click', () => {
           let value = $('#numValue').val();
           console.log(value)
           canvas.clear();
           canvas.renderAll();
           let text = new fabric.Textbox(value, {
            left: canvas.width * 0.5,
            top: canvas.height * 0.5,
            originX: "center",
            originY: 'center',
            fill: 'rgb(64, 64, 153)',
            stroke: 'rgb(255,255,255)',
            strokeWidth: 1
          });
          if (type == 'num') {
            text.set({fontSize: 165});
            canvas.add(text);
            let imgSrc=canvas.toDataURL({format:'png'});
            app.ExternalInterface.changeTexture('10', 'Texture.019', imgSrc);
          } else {
            text.set({fontSize: 60});
            canvas.add(text);
            let imgSrc=canvas.toDataURL({format:'png'});
            app.ExternalInterface.changeTexture('PLAYER', 'Texture.004', imgSrc);
          }
        //   console.log(imgSrc);
          closeTab();
          scrollToZoro();
       })
    }
    
     // 点击图片添加到canvas
     let addCanvasPic = (o) => {
            canvas.clear();
            canvas.renderAll()
            fabric.loadSVGFromURL(o, (objects, options) => {
                let obj = fabric.util.groupSVGElements(objects, options);
                    let cw = canvas.width;
                    let ch = canvas.height;
                    let ow = obj.width;
                    let oh = obj.height;
                    let per;

                    per = (cw / ow > ch / oh ? ch / oh : cw / ow) / 1.3;
                    
                    console.log(per)
                    obj.scale(per).set({
                        left: canvas.width * 0.5,
                        top: canvas.height * 0.5,
                        originX: "center",
                        originY: 'center',
                    });
                    canvas.add(obj)
                    let imgSrc=canvas.toDataURL({format:'png'});
                    app.ExternalInterface.changeTexture('LOGO', 'Texture', imgSrc);
                    $('#picTab').css({'display':'none'});
            });

    }
    createPicTab = () => {
        $('#picTab').css({'display':'block'});
        const ulStyle = `position: absolute; width: 100%; height: 100%;`;
        const liStyle = `float: left; width: 3rem; height: 3rem; margin: .4rem .3rem; border: 1px solid #ccc;`;
        $('#picTab').html(`
            <ul style='${ulStyle}'>
                ${imgList.map( v => `
                    <li src='${v.src}' style='${liStyle} background:url(${v.src}) center/contain no-repeat;'></li>
                `).join('')}
            </ul>
        `);
        $('#picTab ul').on('click', e => {
            let index = $('#picTab ul>li').indexOf(e.target);
            console.log(index);
            console.log(e.target);
            if (index != -1) {
                let src = $(e.target).attr('src');
                console.log(src)
                addCanvasPic(src);
            }
        });
    }
    




});